package com.edu.juc.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞的方式和异步编程的设计理念相违背，而轮询的方式会耗费无谓的CPU资源。
 * CompletableFuture提供了一种观察者模式类似的机制，可以让任务执行完成后通知监听的一方。
 */
public class CompletableFutureTest3 {
    public static void main(String[] args) {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            int random = (int) (Math.random() * 10);
            if (random > 5) {
                System.out.println("任务执行成功：" + random);
                return random;
            } else {
                System.out.println("任务执行失败：" + random);
                throw new RuntimeException("任务执行失败");
            }
        }, singleThreadExecutor).whenComplete((result, ex) -> {
            if (ex == null) {
                System.out.println("任务执行成功：" + result);
            } else {
                System.out.println("任务执行失败：" + ex.getMessage());
            }
        });

        singleThreadExecutor.shutdown();
    }
}
